package com.company.project.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.company.project.entity.*;
import com.company.project.mapper.SysDeptMapper;
import com.company.project.mapper.SysRoleDeptMapper;
import com.company.project.mapper.SysRoleMapper;
import com.company.project.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

/**
 * 角色
 *
 * @author wenbin
 * @version V1.0
 * @date 2020年3月18日
 */
@Service("sysRoleDictService")
@Slf4j
public class SysRoleDictServiceImpl implements SysRoleDictService {
    @Resource
    private SysRoleMapper sysRoleMapper;
    @Resource
    private SysDeptMapper sysDeptMapper;
    @Resource
    private SysRoleDeptMapper sysRoleDeptMapper;
    @Resource
    private HttpSessionService httpSessionService;
    @Resource
    private UserService userService;


    public JSONArray getRoles(SysUser user) {
        //通过access_token拿userId
        String userId = httpSessionService.getCurrentUserId();
        SysUser sysUser = userService.getById(userId);
        if (StringUtils.isEmpty(sysUser)) {
            return new JSONArray();
        }
        LambdaQueryWrapper<SysRole> queryWrapper = Wrappers.lambdaQuery();
        if (!org.apache.commons.lang.StringUtils.equals("0",sysUser.getDeptId())) {
            //管理员可查看全部 其他能看自己下级
            SysDept sysDept = sysDeptMapper.selectById(sysUser.getDeptId());
            LambdaQueryWrapper<SysDept> queryWrapperDept = Wrappers.lambdaQuery();
            queryWrapperDept.select(SysDept::getId).like(SysDept::getRelationCode, sysDept.getDeptNo());
            //所有部门
            List<Object> deptList = sysDeptMapper.selectObjs(queryWrapperDept);
            if (!StringUtils.isEmpty(deptList)) {
                LambdaQueryWrapper<SysRoleDeptEntity> queryWrapperRD = Wrappers.lambdaQuery();
                queryWrapperRD.select(SysRoleDeptEntity::getRoleId).in(SysRoleDeptEntity::getDeptId,deptList);
                //查询全部角色id
                List<Object> roleIds = sysRoleDeptMapper.selectObjs(queryWrapperRD);
                queryWrapper.in(SysRole::getId,roleIds);
            }
        }

        queryWrapper.orderByDesc(SysRole::getCreateTime);
        //获取明细
        List<SysRole> list = sysRoleMapper.selectList(queryWrapper);
        return JSONArray.parseArray(JSON.toJSONString(list));
    }
}
